package cn.net;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

public class sendRevicve_demo {

	public static void main(String[] args) throws InterruptedException {
		new recive().start();
		Thread.sleep(10);
		new send().start();
	}

}
class recive extends Thread{
	@Override
	public void run() {
		try {
			DatagramSocket sc = new DatagramSocket(6666);
			DatagramPacket pac = new DatagramPacket(
					new byte[1024],
					1024
					);
			while(true) {
				sc.receive(pac);
				byte[] arr = pac.getData();
				int len = pac.getLength();
				String res = new String(arr,0,len);
				String ip = pac.getAddress().getHostAddress();
				int port = pac.getPort();
				System.out.println(ip+":"+port+": "+res);
				if("quit".equals(res)) {
					Thread.sleep(2000);
					return ;
				}
			}
		} catch ( Exception e) {
			
			e.printStackTrace();
		}
	}
}
class send extends Thread{
	@Override
	public void run() {
		Scanner sc = new Scanner(System.in);
		DatagramSocket soc;
		try {
			soc = new DatagramSocket();
		
			while(true) {
				String line = sc.nextLine();
				if("quit".equals(line)) break;
				DatagramPacket pac = new DatagramPacket(
						line.getBytes(),
						line.getBytes().length,
						InetAddress.getByName("127.0.0.1"),
						6666
						);
				soc.send(pac);
			}
		} catch (Exception e) {
			
			e.printStackTrace();
		}
	}
}
